package engine.systems.render.particle
{
	import ash.tools.ListIteratingSystem;
	
	import engine.classes.enumerations.SystemPriority;
	import engine.utils.EntityUtils;
	
	import org.flintparticles.common.renderers.SpriteRendererBase;
	import org.flintparticles.twoD.emitters.Emitter2D;
	
	public class ParticleSystem extends ListIteratingSystem
	{
		public function ParticleSystem()
		{
			super(ParticleNode, updateNode, nodeAdded, nodeRemoved);
			
			this.priority = SystemPriority.SPATIAL;
		}
		
		private function updateNode(node:ParticleNode, time:Number):void
		{
			var emitter:Emitter2D = node.particle._emitter;
			
			if(EntityUtils.sleeping(node.entity))
			{
				emitter.pause();
				return;
			}
			else emitter.resume();
			
			var x:Number 		= node.spatial.x;
			var y:Number 		= node.spatial.y;
			var rotation:Number = node.spatial.rotation;
			
			if(node.offset)
			{
				x 			+= node.offset.x;
				y 			+= node.offset.y;
				rotation 	+= node.offset.rotation;
			}
			
			emitter.x 			= x;
			emitter.y 			= y;
			emitter.rotation 	= rotation;
			
			emitter.update(time);
			
			if(node.particle.remove)
			{
				emitter.counter.stop();
				
				if(emitter.particles.length <= 0)
					this.group.removeEntity(node.entity);
			}
		}
		
		private function nodeAdded(node:ParticleNode):void
		{
			node.render.locked = true;
			
			with(node.render.display)
			{
				addEmitter(node.particle.emitter);
				x = 0;
				y = 0;
			}
		}
		
		private function nodeRemoved(node:ParticleNode):void
		{
			node.render.locked = false;
			
			with(node.render.display)
			{
				removeEmitter(node.particle.emitter);
			}
		}
	}
}